<template>
    <div>
        <el-upload
                action="https://jsonplaceholder.typicode.com/posts/"
                list-type="picture-card"
                size="mini"
                :on-remove="handleRemove"
                :before-upload="beforeAvatarUpload"
                :file-list="value"
                :multiple="false"
                :on-error="errorCallback"
                :on-success="change">
            <i class="el-icon-plus"></i>
        </el-upload>
    </div>
</template>
<script>
    export default {
        name: 'upload',
        data() {
            return {
                value: (this.defaultValue && this.defaultValue !== '') ? [{
                    name: this.fieldName,
                    url: this.defaultValue
                }] : [],
                dialogImageUrl: '',
                dialogVisible: false
            }
        },
        props: {
            dataType: String,
            fieldName: String,
            selectCb: Function,
            defaultValue: {}
        },
        methods: {
            change(response, file, fileList) {
                this.$emit('selectCb', {
                    fieldName: this.fieldName,
                    value: file.url
                })
            },
            errorCallback(err, file, fileList) {
                this.$message.error('图片上传失败' + err);
            },
            handleRemove() {
                this.$emit('selectCb', {
                    fieldName: this.fieldName,
                    value: ''
                })
            },
            beforeAvatarUpload(file) {
                const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
                const isLt2M = file.size / 1024 < 200;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是JPG或者PNG格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 200K!');
                }
                return isJPG && isLt2M;
            }
        },
        watch: {
            defaultValue: function (n) {
                if (n && n !== '') {
                    this.value = [{
                        name: this.fieldName,
                        url: n
                    }]
                }
            }
        }
    }
</script>
